from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from xyz.serializers.user import UserRegiestSerizlizers

from django.contrib.auth import authenticate


class UserRegiestView(APIView):
    def post(self, request):
        serizlizers = UserRegiestSerizlizers(data=request.data)
        serizlizers.is_valid(raise_exception=True)
        user = serizlizers.save()
        return Response({
            'id': user.id,
            'username': user.username,
            'mobile': user.mobile,
            'token': user.token,
            'avatar': user.avatar
        })


class UserLoginView(APIView):
    def post(self, request):
        user = authenticate(**request.data)
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'id': user.id,
            'mobile': user.mobile,
            'token': token,
            'avatar': user.avatar,
            'username': user.username
        })
